<?php
/**
 * Created by PhpStorm.
 * User: chenx
 * Date: 18-2-27
 * Time: 下午9:06
 */

namespace common\service;


use common\models\Menu;

class MenuService extends BaseService
{


    /**
     * 获取所有父级的名称和url
     * @param   int  $menu_id
     * @return array
     */
    public static function getParentsMenu($menu_id = 0)
    {
        static $list = [];
        $menu = Menu::findOne(['menu_id' => $menu_id]);
        $list[] = $menu->toArray();
        if($menu['parent_code'] == 0){
            return $list;
        }
        return self::getParentsMenu($menu['parent_code']);
    }

    /**
     * 树形获取菜单
     * @param $arr
     * @param int $pid
     * @param int $level
     * @return array
     */
    public static function getMenus($arr,$pid=0,$level=0){
        $list = [];
        foreach($arr as $key=>$value)
        {
            if($value['parent_code'] == $pid)
            {
//                $value['level'] = $level;
                $value['title'] = $value['menu_name'];
                $value['href'] = GlobalUrlService::buildAdminUrl($value['url']);
                $value['spread'] = false;
                array_push($list,$value);
            }
        }
        if(empty($list)) {
            return $list;
        }else{
            foreach($list as $key=>$value)
            {
                $list[$key]['children'] = self::getMenus($arr,$value['menu_id'],$level + 1);
            }
        }
        return $list;//递归出口
    }


    /**
     * 获取二维菜单列表
     * @param $arr
     * @param int $pid
     * @param int $level
     * @return array
     */
    public static function getCategory($arr,$pid=0,$level=0){
        $list = [];
        foreach($arr as $key=>$value)
        {
            if($value['parent_code'] == $pid)
            {
//                $value['level'] = $level;
                array_push($list,$value);
            }
        }
        if(empty($list)) {
            return $list;
        }else{
            $data = [];
            foreach($list as $key=>$value)
            {
                array_push($data,$value);
                $data = array_merge($data,self::getCategory($arr,$value['menu_id'],$level + 1));
            }
        }
        return $data;//递归出口
    }

    /**
     * 添加菜单权限选中状态
     * @param  array $menus
     * @param  array $current_menu_ids
     * @return array
     */
    public static function addCheckStatus($menus,$current_menu_ids){

        if(empty($menus)){
            return [];
        }
        foreach ($menus as &$menu){
            if(in_array($menu['menu_id'],$current_menu_ids)){
                $menu['checked'] = 'true';
            }else{
                $menu['checked'] = 'false';
            }
        }
        return $menus;
    }

}